package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.common.dto.pyq.FeedMedia;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.PyqJobStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.MsgSplitUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.feign.uzaicms.CmsDtkTbGoodsDetailDto;
import com.uzai.console.dto.pyq.pyqgoods.PyqJobBatchSendDao;
import com.uzai.console.dto.pyq.pyqgoods.PyqJobSendDao;
import com.uzai.console.dto.pyq.pyqmaterial.TurnlinkDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.PyqDevicePlan;
import com.uzai.console.entity.PyqJob;
import com.uzai.console.entity.PyqMaterial;
import com.uzai.console.mapper.PyqDevicePlanMapper;
import com.uzai.console.mapper.PyqJobMapper;
import com.uzai.console.mapper.PyqMaterialMapper;
import com.uzai.console.service.feign.UzaiCmsFeignService;
import com.uzai.console.service.pyq.PyqGoodsSyncService;
import com.uzai.console.service.pyq.PyqJobDetailService;
import com.uzai.console.service.pyq.PyqJobSyncService;
import com.uzai.console.service.pyq.PyqMaterialService;
import com.uzai.console.vo.cms.tbgoods.CmsTbGoodsInfoVo;
import com.uzai.console.vo.cms.tbgoods.DtkGoodsDetailVo;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 发送朋友圈异步执行线程
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqGoodsSyncServiceImpl implements PyqGoodsSyncService {

    Logger logger = LoggerFactory.getLogger(PyqGoodsSyncServiceImpl.class);

    @Autowired
    private PyqJobMapper pyqJobMapper;
    @Autowired
    private PyqJobDetailService pyqJobDetailService;
    @Autowired
    private PyqMaterialService pyqMaterialService;
    @Autowired
    private PyqJobSyncService pyqJobSyncService;
    @Autowired
    private UzaiCmsFeignService uzaiCmsFeignService;
    @Autowired
    private PyqMaterialMapper pyqMaterialMapper;
    @Autowired
    private PyqDevicePlanMapper pyqDevicePlanMapper;

    /**
     * 添加群发任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param
     * @return null
     */
    @Override
    @Async("taskExecutor")
    public void  batchAddJobSync(PyqJobBatchSendDao pyqJobBatchSendDao, List<Long> deviceUniqueIdList){

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            return;
        }

        Integer now = DateUtil.getNowTime();
        //页面填写的发送时间
        Integer sendTime_page = now + 5*60; //当前时间+5分钟
        //页面填写了发送时间
        if(pyqJobBatchSendDao.getSendTime() != null ){
            sendTime_page = pyqJobBatchSendDao.getSendTime();
        }
        Integer timeInterval = 0;
        //间隔时间,页面填写了间隔时间，单位为分钟
        if(pyqJobBatchSendDao.getTimeInterval() != null){
            timeInterval = pyqJobBatchSendDao.getTimeInterval() * 60;
        }
        List<String> itemidList = pyqJobBatchSendDao.getItemidList();
        if(itemidList != null && itemidList.size() > 0){
            for (int i=0; i<itemidList.size(); i++){
                try{
                    String itemid = itemidList.get(i);
                    CmsDtkTbGoodsDetailDto cmsDtkTbGoodsDetailDto = new CmsDtkTbGoodsDetailDto();
                    cmsDtkTbGoodsDetailDto.setItemId(itemid);
                    UzaiRespVo<DtkGoodsDetailVo> uzaiRespVo = uzaiCmsFeignService.dtkGoodsDetailSingle(cmsDtkTbGoodsDetailDto);
                    logger.info("请求大淘客商品详情接口- para={}, uzaiRespVo={}", JSONObject.toJSONString(cmsDtkTbGoodsDetailDto), JSONObject.toJSONString(uzaiRespVo));
                    if(uzaiRespVo.getCode() == 200) {
                        DtkGoodsDetailVo dtkGoodsDetailVo = uzaiRespVo.getData();
                        if (dtkGoodsDetailVo != null) {
                            //实际发送时间累加间隔时间(第一次不增加)
                            Integer sendTime_data = sendTime_page + timeInterval * i;

                            PyqJob pyqJob = new PyqJob();
                            pyqJob.setId(IdWorker.getId());
                            pyqJob.setMerId(pyqJobBatchSendDao.getMerId());
                            pyqJob.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                            pyqJob.setStatus(PyqJobStatusEnum.NOSTART.getValue());
                            pyqJob.setType(pyqJobBatchSendDao.getType());
                            pyqJob.setSource(0); //手动发送
                            pyqJob.setPlatform(pyqJobBatchSendDao.getPlatform());
                            pyqJob.setDevicePlanId(pyqJobBatchSendDao.getDevicePlanId());
                            pyqJob.setItemId(itemid);
                            pyqJob.setCouponId(dtkGoodsDetailVo.getCouponId());

                            //图片
                            List<String> imgList = new ArrayList<>();
                            //添加营销主图
                            if(StringUtils.isNotBlank(dtkGoodsDetailVo.getMarketingMainPic())){
                                imgList.add(dtkGoodsDetailVo.getMarketingMainPic());
                            }

                            //添加商品主图
                            if(StringUtils.isNotBlank(dtkGoodsDetailVo.getMainPic())){
                                imgList.add(dtkGoodsDetailVo.getMainPic());
                            }

                            //添加轮播图
                            String lunboImgs = Tools.getStr(dtkGoodsDetailVo.getImgs());
                            String[] lunboImgList = lunboImgs.split(",");
                            if(lunboImgList != null){
                                for (String lunboImg : lunboImgList){
                                    if(StringUtils.isNotBlank(lunboImg)){
                                        imgList.add(lunboImg);
                                    }
                                }
                            }
                            if(StringUtils.isNotBlank(pyqJobBatchSendDao.getCustomImg())){
                                imgList.add(Tools.getStr(pyqJobBatchSendDao.getCustomImg()));
                            }
                            if(imgList.size() > 9){
                                imgList = imgList.subList(0, 9);
                            }

                            //新版朋友圈接口新增加字段
                            //封装附件类型
                            int attachType = 2; //默认图文
                            //封装附件对象
                            List<FeedMedia> feedMediaList = new ArrayList<>();
                            //封装视频号信息
                            String videoNumber = null;

                            if(imgList != null && imgList.size() > 0){
                                for (String item : imgList){
                                    if(StringUtils.isNotBlank(item)){
                                        FeedMedia feedMedia = new FeedMedia();
                                        feedMedia.setMediaType(2);
                                        feedMedia.setUrl(item);
                                        feedMediaList.add(feedMedia);
                                    }
                                }
                            }
                            pyqJob.setAttachType(2);//图文
                            pyqJob.setFeedMedia(Tools.getStrNull(JSONObject.toJSONString(feedMediaList)));
                            pyqJob.setVideoNumber(videoNumber);
                            pyqJob.setImgs(null);  //新版朋友圈接口，img不存放任何东西

                            pyqJob.setCouponVal(Tools.getDouble(dtkGoodsDetailVo.getCouponPrice()));
                            pyqJob.setFinalPrice(Tools.getDouble(dtkGoodsDetailVo.getActualPrice()));
                            pyqJob.setContentId(pyqJobBatchSendDao.getContentId());
                            pyqJob.setCommentId(pyqJobBatchSendDao.getCommentId());
                            pyqJob.setTotalCount(deviceUniqueIdList.size());
                            pyqJob.setCreateTime(now);
                            pyqJob.setUpdateTime(now);
                            pyqJob.setSendTime(sendTime_data);

                            //朋友圈内容替换变量
                            String content = Tools.getStr(pyqJobBatchSendDao.getContent());

                            content = content.replace("[商品标题]",Tools.getStr(dtkGoodsDetailVo.getTitle()))
                                    .replace("[文案]",Tools.getStr(dtkGoodsDetailVo.getDesc()))
                                    .replace("[原价]",  String.valueOf(Tools.getDouble(dtkGoodsDetailVo.getOriginalPrice()).doubleValue()))
                                    .replace("[券后价]", String.valueOf(Tools.getDouble(dtkGoodsDetailVo.getActualPrice()).doubleValue()));
                            pyqJob.setContent(content);

                            //评论内容替换变量
                            String commentContent = Tools.getStr(pyqJobBatchSendDao.getCommentContent());
                            commentContent = commentContent.replace("[商品标题]",Tools.getStr(dtkGoodsDetailVo.getTitle()))
                                    .replace("[文案]",Tools.getStr(dtkGoodsDetailVo.getDesc()))
                                    .replace("[原价]",  String.valueOf(Tools.getDouble(dtkGoodsDetailVo.getOriginalPrice()).doubleValue()))
                                    .replace("[券后价]", String.valueOf(Tools.getDouble(dtkGoodsDetailVo.getActualPrice()).doubleValue()));
                            //去空评论
                            List<String> commentContentList = JSONObject.parseArray(commentContent, String.class);
                            if(commentContentList != null && commentContentList.size() > 0){
                                commentContentList.removeIf(s ->  StringUtils.isBlank(s));
                                commentContent = JSONObject.toJSONString(commentContentList);
                            }
                            pyqJob.setCommentContent(commentContent);

                            //后台添加发送明细
                            pyqJobSyncService.addJobSync(pyqJob, deviceUniqueIdList, pyqJobBatchSendDao.getDomain());

                        }
                    }
                }catch (Exception e){

                }
            }
        }

    }


    /**
     * 单个商品添加群发任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param
     * @return null
     */
    @Override
    @Async("taskExecutor")
    public void  addJobSync(PyqJobSendDao pyqJobSendDao, List<Long> deviceUniqueIdList){

        logger.info("发送朋友圈的机器人数：num={}",deviceUniqueIdList.size());

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            return;
        }

        Integer now = DateUtil.getNowTime();
        //发送时间
        Integer sendTime = now + 5*60;  //当前时间+5分钟
        //页面填写了发送时间
        if(pyqJobSendDao.getSendTime() != null ){
            sendTime = pyqJobSendDao.getSendTime();
        }

        PyqJob pyqJob = new PyqJob();
        pyqJob.setId(IdWorker.getId());
        pyqJob.setMerId(pyqJobSendDao.getMerId());
        pyqJob.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
        pyqJob.setStatus(PyqJobStatusEnum.NOSTART.getValue());
        pyqJob.setType(pyqJobSendDao.getType());
        pyqJob.setSource(0); //手动发送
        pyqJob.setPlatform(pyqJobSendDao.getPlatform());
        pyqJob.setDevicePlanId(pyqJobSendDao.getDevicePlanId());
        pyqJob.setItemId(pyqJobSendDao.getItemid());
        pyqJob.setCouponId(pyqJobSendDao.getActivityid());
        //图片
        List<String> imgList = pyqJobSendDao.getImgList();
        if(imgList != null && imgList.size() > 9){
            imgList = imgList.subList(0, 9);
        }

        //新版朋友圈接口新增加字段
        //封装附件类型
        int attachType = 2; //默认图文
        //封装附件对象
        List<FeedMedia> feedMediaList = new ArrayList<>();
        //封装视频号信息
        String videoNumber = null;

        if(imgList != null && imgList.size() > 0){
            for (String item : imgList){
                if(StringUtils.isNotBlank(item)){
                    FeedMedia feedMedia = new FeedMedia();
                    feedMedia.setMediaType(2);
                    feedMedia.setUrl(item);
                    feedMediaList.add(feedMedia);
                }
            }
        }
        pyqJob.setAttachType(2);//图文
        pyqJob.setFeedMedia(Tools.getStrNull(JSONObject.toJSONString(feedMediaList)));
        pyqJob.setVideoNumber(videoNumber);
        pyqJob.setImgs(null);  //新版朋友圈接口，img不存放任何东西

        pyqJob.setCouponVal(pyqJobSendDao.getCouponmoney());
        pyqJob.setFinalPrice(pyqJobSendDao.getItemendprice());
        pyqJob.setContentId(pyqJobSendDao.getContentId());
        pyqJob.setCommentId(pyqJobSendDao.getCommentId());
        pyqJob.setTotalCount(deviceUniqueIdList.size());
        pyqJob.setCreateTime(now);
        pyqJob.setUpdateTime(now);
        pyqJob.setSendTime(sendTime);

        //朋友圈内容替换变量
        String content = Tools.getStr(pyqJobSendDao.getContent());
        //券后价
        Double itemendprice = Tools.getDouble(pyqJobSendDao.getItemendprice());
        //优惠券金额
        Double couponmoney = Tools.getDouble(pyqJobSendDao.getCouponmoney());
        //原价 itemprice
        Double itemprice = Tools.getDouble(pyqJobSendDao.getItemprice());
        content = content.replace("[商品标题]",Tools.getStr(pyqJobSendDao.getItemtitle()))
                .replace("[文案]",Tools.getStr(pyqJobSendDao.getDesc()))
                .replace("[原价]",  String.valueOf(itemprice.doubleValue()))
                .replace("[券后价]", String.valueOf(itemendprice.doubleValue()));
        pyqJob.setContent(content);

        //评论内容替换变量
        String commentContent = Tools.getStr(pyqJobSendDao.getCommentContent());
        commentContent = commentContent.replace("[商品标题]",Tools.getStr(pyqJobSendDao.getItemtitle()))
                .replace("[文案]",Tools.getStr(pyqJobSendDao.getDesc()))
                .replace("[原价]",  String.valueOf(itemprice.doubleValue()))
                .replace("[券后价]", String.valueOf(itemendprice.doubleValue()));
        //去空评论
        List<String> commentContentList = JSONObject.parseArray(commentContent, String.class);
        if(commentContentList != null && commentContentList.size() > 0){
            commentContentList.removeIf(s ->  StringUtils.isBlank(s));
            commentContent = JSONObject.toJSONString(commentContentList);
        }
        pyqJob.setCommentContent(commentContent);

        //后台添加发送明细
        pyqJobSyncService.addJobSync(pyqJob, deviceUniqueIdList, pyqJobSendDao.getDomain());

        //保存为素材
        if(Tools.getInteger(pyqJobSendDao.getSaveMaterialFlag()).intValue() == 1){ //保存素材
            PyqMaterial pyqMaterial = new PyqMaterial();
            pyqMaterial.setId(IdWorker.getId());
            pyqMaterial.setMerId(pyqJob.getMerId());
            pyqMaterial.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
            pyqMaterial.setType(pyqJob.getType());
            pyqMaterial.setPlatform(pyqJob.getPlatform());
            pyqMaterial.setDevicePlanId(pyqJob.getDevicePlanId());
            pyqMaterial.setItemId(pyqJob.getItemId());
            pyqMaterial.setCouponId(pyqJob.getCouponId());
            pyqMaterial.setCouponVal(pyqJob.getCouponVal());
            pyqMaterial.setFinalPrice(pyqJob.getFinalPrice());
            pyqMaterial.setContentId(pyqJob.getContentId());
            pyqMaterial.setContent(pyqJob.getContent());
            pyqMaterial.setImgs(pyqJob.getImgs());
            pyqMaterial.setCommentId(pyqJob.getCommentId());
            pyqMaterial.setCommentContent(pyqJob.getCommentContent());
            //新版朋友圈接口新增加字段
            pyqMaterial.setAttachType(pyqJob.getAttachType());
            pyqMaterial.setVideoNumber(pyqJob.getVideoNumber());
            pyqMaterial.setFeedMedia(pyqJob.getFeedMedia());
            pyqMaterial.setImgs(null);  //新版朋友圈接口，img不存放任何东西
            pyqMaterial.setCreateTime(now);
            pyqMaterial.setUpdateTime(now);
            pyqMaterialMapper.insert(pyqMaterial);
        }
    }

}
